import React, { useEffect, useState, useImperativeHandle, forwardRef } from 'react';
import Router, { withRouter } from '@/router/renderRouter';
import { Card, Row, Col, Input, Select, Button, message, Spin, Modal } from 'antd';
import { useSyncCallback, deepclone } from '@/utils'
import { CopyToClipboard } from 'react-copy-to-clipboard';

import { 
  merchantInfo, 
  merchantClassList,
  merchantUpdate,
  
  merchantResetTransPwd,
  merchantResetPrivateKey,
  merchantResetLoginPwd,
  resetUserSecret,
  
} from '@/api/api'
import './index.scss'; 
let orCToken = {}

const MerchantInfo = forwardRef((props, ref) => {
  const { route, history } = props
  const [id, setId] = useState('');
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [modalType, setModalType] = useState('');
  const [password, setPassword] = useState('');
  const [info, setInfo] = useState(null);
  const [loading, setLoading] = useState(false)
  const [merchantOptions, setMerchantOptions] = useState([]);
  // 等state改变后再执行
  const searchData = useSyncCallback(() => {
    handleFinish()
  })
  
  const merchantClassListHanlder = async () => {
    try {
      let res = await merchantClassList()
      if(res.code === 0) {
        let arr = []
        res.data.forEach(item=>{
          arr.push({
            value: item.id+'',
            label: item.className,
          })
        })
        setMerchantOptions(arr)
      }
    } catch(error) {
      console.log(error)
    }
  }
  const changeValue = (name,val) =>{
    let obj = deepclone(info)
    obj[name] = val;
    setInfo(obj)
  }
  const reset = async (type) => {
    try {
      setLoading(true)
      let res;
      let params = {}
      setModalType(type)
      if(type === 'loginPwd'){
        params.merchantId = info.id;
        res = await merchantResetLoginPwd(params);
      }else if(type === 'transPwd'){
        params.merchantId = info.id;
        res = await merchantResetTransPwd(params);
      }else if(type === 'openSecondValid'){
        params.userId = info.id;
        res = await resetUserSecret(params);
      }else if(type === 'merchantPrivateKey'){
        params.merchantId = info.id;
        res = await merchantResetPrivateKey(params);
      }
      setLoading(false)
      if(res.code === 0) {
        if(type === 'loginPwd' || type === 'transPwd' || type === 'merchantPrivateKey'){
          setPassword(res.data);
          setIsModalOpen(true);
        }else{
          message.success('重置成功')
        }
        searchData()
      }
    } catch(error) {
      console.log(error)
    }
  }
  const close = () => {
    setIsModalOpen(false)
    setPassword('')
  }
  const handleFinish = async () => {
    try {
      let params = {
        id,
      }
      if (typeof orCToken.source === 'function') {
        orCToken.source('终止请求'); //取消请求
      }
      setLoading(true)
      let res = await merchantInfo(params, orCToken)
      if(res.code === 0) {
        setInfo(res.data)
      }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  const save = async () =>{
    try {
      let params = {
        merchantId: info.id,
        nickName: info.nickName,
        status: info.status,
        merchantClassId: info.merchantClass,
        handicapInfo: info.merchantHandicap,
        remark: info.riskRemark,
      }
      if (typeof orCToken.source === 'function') {
        orCToken.source('终止请求'); //取消请求
      }
      setLoading(true)
      let res = await merchantUpdate(params, orCToken)
      if(res.code === 0) {
        message.success('修改成功')
        handleFinish()
      }
      setLoading(false)
    } catch(error) {
      console.log(error)
    }
  }
  const back = () =>{
    props.setPageType('index')
    props.setParams(null)
  }
  useEffect(() => {
    if(props.params){
    	setId(props.params.userId)
    }
    merchantClassListHanlder()
    searchData()
    return () => { 
    };
  // eslint-disable-next-line react-hooks/exhaustive-deps
  } , [])
  useImperativeHandle(ref, () => ({
    searchData,
  }))
  return (
    <>
      <div>
        <Spin spinning={loading}>
          <Card title="商户资料">
            <Row className="row">
              <Col span={8}>商户账号：{info&&info.userName || '--'}</Col>
              <Col span={8}>商户编号：{info&&info.merchantCode || '--'}</Col>
              <Col span={8}>开户时间：{info&&info.registerTime || '--'}</Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>登录密码：{info&&info.hasLoginPwd ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasLoginPwd===true
                  ?
                  <a className="a" onClick={()=>{reset('loginPwd')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8}>
                <span>商户余额：{info&&info.balanceAmount}</span>
                <a className="a" onClick={()=>{props.open(info)}}>修改余额</a>
              </Col>
              <Col span={8} className="flex">
                <span>商户名称：</span>
                <Input style={{width: '150px'}} value={info&&info.nickName} onChange={(e)=>{changeValue('nickName',e.target.value)}} />
              </Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>交易密码：{info&&info.hasTransPwd ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasTransPwd===true
                  ?
                  <a className="a" onClick={()=>{reset('transPwd')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8}>商户类型：{info&&info.merchantType ? (info.merchantType === 1 ? '现金' : '信用') : '--'}</Col>
              <Col span={8} className="flex">
                <span>商户状态：</span>
                <Select 
                  style={{width: '150px'}}
                  value={info&&info.status}
                  onChange={(e)=>{changeValue('status',e)}}
                  options={[
                   {value: 1, label: '启用'},
                   {value: 2, label: '停用'},
                   {value: 3, label: '冻结资金'},
                  ]} 
                />
              </Col>
            </Row>
            <Row className="row">
              <Col span={8}>
                <span>二次验证：{info&&info.openSecondValid ? '已设置' : '未设置'}</span>
                {
                  info&&info.openSecondValid===true
                  ?
                  <a className="a" onClick={()=>{reset('openSecondValid')}}>重置</a>
                  :
                  ''
                }
              </Col>
              <Col span={8} className="flex">
                <span>商户分类：</span>
                <Select 
                  style={{width: '150px'}}
                  value={info&&info.merchantClass}
                  onChange={(e)=>{changeValue('merchantClass',e)}}
                  options={merchantOptions} 
                />
              </Col>
              <Col span={8}>
                <span>商户秘钥：{info&&info.hasMerchantPrivateKey ? '已设置' : '未设置'}</span>
                {
                  info&&info.hasMerchantPrivateKey===true
                  ?
                  <a className="a" onClick={()=>{reset('merchantPrivateKey')}}>重置</a>
                  :
                  ''
                }
              </Col>
            </Row>
            <Row className="row">
              <Col span={12}>钱包地址：{info&&info.memberWallet || '--'}</Col>
            </Row>
            <Row className="row">
              <Col span={24} className="flex">
                <span>商户盘口：</span>
                <Input.TextArea 
                  value={info&&info.merchantHandicap} 
                  onChange={(e)=>{changeValue('merchantHandicap',e.target.value)}}
                  rows={3} />
              </Col>
            </Row>
            <Row className="row">
              <Col span={24} className="flex">
                <span>风控备注：</span>
                <Input.TextArea 
                  value={info&&info.riskRemark} 
                  onChange={(e)=>{changeValue('riskRemark',e.target.value)}}
                  rows={3} />
              </Col>
            </Row>
            <div style={{display: 'flex','justifyContent': 'space-around'}}>
              <Button onClick={()=>{back()}}>取消</Button>
              <Button type="primary" loading={loading} onClick={()=>{save()}}>确定</Button>
            </div>
          </Card>
        </Spin>
        
        <Modal title="提示" visible={isModalOpen} onOk={close} onCancel={close}
        	footer={[
        	  <Button type="primary" style={{marginLeft: '20px'}} onClick={close}>确认</Button>,
        	]}
        >
        	<p>重置{modalType === 'merchantPrivateKey'?'秘钥':'密码'}成功</p>
        	<table>
        		<tr>
        			<td>商户账号 : {info&&info.userName}</td>
        			<td><CopyToClipboard
        				onCopy={()=>message.success('复制成功')}
        				text={info&&info.userName}>
        				<Button type="primary" style={{marginLeft: '20px'}}>复制</Button>
        			</CopyToClipboard></td>
        		</tr>
        		<tr>
        			<td>{modalType === 'merchantPrivateKey'?'商户秘钥':'新密码'} : {password}</td>
        			<td>
        				<CopyToClipboard
        					onCopy={()=>message.success('复制成功')}
        					text={password}>
        					<Button type="primary" style={{marginLeft: '20px'}}>复制</Button>
        				</CopyToClipboard>
        			</td>
        		</tr>
        	</table>
        </Modal>
      </div>
    </>
  )
})
export default MerchantInfo